<template>
  <div class="app-container">
    <el-tabs type="border-card" @tab-click="handleClick">
      <el-tab-pane label="待审核">
        <!-- 表格 -->
        <el-table
          :key="tableKey"
          ref="table"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="顺序" prop="order" align="center" />
          <el-table-column label="拍品编号" prop="shopping_id" align="center" />
          <el-table-column label="拍品名称" header-align="center">
            <template slot-scope="{ row }">
              <el-image
                style="width: 40px; height: 40px; text-align: center"
                :src="$store.state.settings.imgHost + row.image"
                :preview-src-list="[$store.state.settings.imgHost + row.image]"
              />
              <span style="vertical-align: top; margin-left: 10px">{{
                row.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="店铺"
            prop="shopping.shopping_name"
            align="center"
          />
          <el-table-column label="起拍价" prop="price" align="center" />
          <el-table-column label="申请时间" align="center" prop="created_at" />
          <el-table-column label="操作" align="center">
            <template slot-scope="{ row }">
              <el-button
                size="mini"
                plain
                type="primary"
                @click="handleDialog(row)"
              >
                同意上拍
              </el-button>
              <el-button
                size="mini"
                plain
                type="danger"
                @click="handleRefuse(row.id)"
              >
                拒绝
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已拒绝">
        <!-- 表格 -->
        <el-table
          :key="tableKey"
          ref="table"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="拍品名称" header-align="center">
            <template slot-scope="{ row }">
              <el-image
                style="width: 40px; height: 40px; text-align: center"
                :src="$store.state.settings.imgHost + row.image"
                :preview-src-list="[$store.state.settings.imgHost + row.image]"
              />
              <span style="vertical-align: top; margin-left: 10px">{{
                row.name
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price" align="center" />
          <el-table-column label="申请时间" align="center" prop="created_at" />
          <el-table-column label="店铺" prop="shopping.name" align="center" />
          <el-table-column
            label="拒绝原因"
            prop="reject_remark"
            align="center"
          />
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页 -->
    <div v-if="total > 0" style="text-align: right">
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.per_page"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="上拍"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="40%"
      @closed="dialogClosed"
    >
      <div style="margin-top: 20px">
        <el-form
          ref="postForm"
          :model="form"
          :rules="rules"
          class="form-container"
          label-width="110px"
        >
          <div class="createPost-main-container">
            <el-form-item label-width="110px" label="排序:">
              <el-input v-model="form.order" class="input-spin" type="number" />
            </el-form-item>
            <el-form-item label-width="110px" label="拍品名称:" prop="name">
              <el-input v-model.trim="form.name" />
            </el-form-item>
            <el-form-item
              label-width="110px"
              label="拍品分类:"
              prop="product_category_id"
            >
              <el-select
                v-model="form.product_category_id"
                placeholder="请选择拍品分类"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in classifyOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label-width="110px" label="起拍价:" prop="price">
              <el-input
                v-model="form.price"
                class="table-input-center"
                type="number"
              />
            </el-form-item>
            <el-form-item
              label-width="110px"
              label="加价幅度:"
              prop="add_money_range"
            >
              <el-input
                v-model="form.add_money_range"
                class="table-input-center"
                type="number"
              />
            </el-form-item>
            <el-form-item label-width="110px" label="估价:" prop="evaluation">
              <el-row>
                <el-col :span="11">
                  <el-input
                    v-model="form.min_money"
                    class="table-input-center"
                    type="number"
                  />
                </el-col>
                <el-col :span="2" style="text-align: center">-</el-col>
                <el-col :span="11">
                  <el-input
                    v-model="form.max_money"
                    class="table-input-center"
                    type="number"
                  />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item
              label-width="110px"
              label="拍卖场次:"
              prop="auction_session_id"
            >
              <el-select
                v-model="form.auction_session_id"
                placeholder="请选择拍卖场次"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in fieldOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label-width="110px"
              label="竞拍保证金:"
              prop="security_deposit"
            >
              <el-input
                v-model="form.security_deposit"
                class="input-spin"
                type="number"
              />
              <div style="color: #aaa">填“0”则不需要保证金</div>
            </el-form-item>
            <el-form-item label="拍品主图:" prop="image">
              <img
                style="
                  width: 148px;
                  height: 148px;
                  display: inline-block;
                  margin-right: 8px;
                  margin-bottom: 8px;
                "
                :src="form.image"
              >
            </el-form-item>
            <el-form-item label="拍品图片:" prop="image">
              <!-- <el-upload
                :file-list="fileList"
                action="#"
                disabled
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                list-type="picture-card"
                :http-request="
                  file => {
                    return uploadImgHandle(file, 'from1');
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    return removeHandle(file, fileList, 'from1');
                  }
                "
              >
                <i class="el-icon-plus"></i>
              </el-upload> -->
              <img
                v-for="(item, index) in fileList"
                :key="index"
                style="
                  width: 148px;
                  height: 148px;
                  display: inline-block;
                  margin-right: 8px;
                  margin-bottom: 8px;
                "
                :src="item.url"
              >
            </el-form-item>
            <!-- <el-form-item
              label-width="110px"
              label="拍品图片:"
              prop="image_url"
            >
              <el-upload
                :file-list="fileList"
                action="#"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG"
                list-type="picture-card"
                :http-request="
                  file => {
                    return uploadImgHandle(file);
                  }
                "
                :on-remove="
                  (file, fileList) => {
                    return removeHandle(file, fileList);
                  }
                "
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item> -->
            <el-form-item label="拍品参数:">
              <el-row>
                <el-col
                  v-for="(item, index) in form._params"
                  :key="index"
                  :span="12"
                >
                  <!-- <el-input
                    v-model="item.value"
                    disabled
                    :placeholder="item.model"
                    :style="index > 1 ? 'margin-top: 10px;' : ''"
                  /> -->
                  {{ item.model }}：{{ item.value }}
                </el-col>
              </el-row>
            </el-form-item>
            <!-- <el-form-item label-width="110px" label="拍品参数:">
              <el-row>
                <el-col
                  :span="12"
                  v-for="(item, index) in form._params"
                  :key="index"
                >
                  <el-input
                    v-model="item.value"
                    :placeholder="item.model"
                    :style="index > 1 ? 'margin-top: 10px;' : ''"
                  />
                </el-col>
              </el-row>
            </el-form-item> -->
            <el-form-item label-width="90px" label="拍品详情:">
              <div v-html="form.content" />
            </el-form-item>
            <el-form-item label-width="110px" label="店铺:">
              <el-input v-model.trim="form.shopping_name" disabled />
            </el-form-item>
            <el-form-item label-width="110px" label="保证金:">
              <el-input
                v-model="form.shopping_security_deposit"
                disabled
                class="input-spin"
                type="number"
              />
            </el-form-item>
            <el-form-item label-width="110px" label="创建时间:">
              <el-date-picker
                v-model="form.created_at"
                type="datetime"
                placeholder="选择创建时间"
                :clearable="false"
                disabled
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label-width="110px" label="会员:">
              <el-input v-model.trim="form.user_info" disabled />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div style="margin-top: 40px; text-align: center">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmit">上拍</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getExhibition,
  putExhibition,
  getField,
  getClassify,
  uploadFile
} from '@/api/common'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'AuctionGoodExhibition',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  data() {
    const validEvaluation = (value, callback, $msgForm, $userMsgForm) => {
      if (!$msgForm.min_money || !$msgForm.max_money) {
        callback(new Error('请输入估价'))
      } else if ($msgForm.min_money < 0) {
        callback(new Error('估价最小值不能小于0'))
      } else if ($msgForm.max_money <= 0) {
        callback(new Error('估价最大值必须大于0'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      dialogVisible: false,
      classifyOptions: undefined,
      fieldOptions: undefined,
      form: {},
      fileList: [],
      listQuery: {
        page: 1,
        per_page: 20,
        source: 3,
        audit_status: 2,
        status: 1
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入拍品名称',
            trigger: 'blur'
          }
        ],
        product_category_id: [
          {
            required: true,
            message: '请选择拍品分类',
            trigger: 'change'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入起拍价',
            trigger: 'blur'
          }
        ],
        add_money_range: [
          {
            required: true,
            message: '请输入加价幅度',
            trigger: 'blur'
          }
        ],
        evaluation: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              validEvaluation(value, callback, this.form, this.$refs.dataForm)
            }
          }
        ],
        auction_session_id: [
          {
            required: true,
            message: '请选择拍卖场次',
            trigger: 'change'
          }
        ],
        security_deposit: [
          {
            required: true,
            message: '请输入竞拍保证金',
            trigger: 'blur'
          }
        ],
        image_url: [
          {
            required: true,
            message: '请上传拍品图片',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {
    this.getClassifyData()
    this.getFieldData()
    this.getList()
  },
  methods: {
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    clearFilter() {
      this.handleFilter()
    },
    handleClick(tab) {
      this.listQuery.audit_status = tab.index == 0 ? 2 : 0
      this.handleFilter()
    },
    removeHandle() {
      this.form.image_url = undefined
      this.fileList = []
    },
    uploadImgHandle(e) {
      const formData = new FormData()
      formData.append('file', e.file)
      uploadFile(formData).then((res) => {
        const image = res.data
        this.fileList.push({
          url: this.$store.state.settings.imgHost + image
        })
        this.$set(
          this.form,
          'image_url',
          this.$store.state.settings.imgHost + image
        )
      })
    },
    handleDialog(row) {
      this.form.image_url = undefined
      this.dialogVisible = true
      this.fileList = []
      this.form = Object.assign({}, row)
      if (this.form.shopping) {
        this.form['shopping_name'] = this.form.shopping.shopping_name
        this.form['shopping_security_deposit'] =
          this.form.shopping.security_deposit
      }
      if (this.form.user && this.form.user.name && this.form.user.user) {
        this.form['user_info'] =
          this.form.user.name + '(' + this.form.user.user + ')'
      }
      if (this.form.params && this.form.params != 'null') {
        this.form['params'] = JSON.parse(this.form.params)
        if (this.form.params.length > 0) {
          this.form['_params'] = []
          this.form.params.forEach((res) => {
            for (const i in res) {
              this.form['_params'].push({
                model: i,
                value: res[i]
              })
            }
          })
        }
      }
      if (row.image_list && row.image_list != 'null') {
        this.form['image_list'] = JSON.parse(this.form['image_list'])
        if (this.form['image_list'].length > 0) {
          this.form['image_list'].forEach((res) => {
            res = this.$store.state.settings.imgHost + res
            this.fileList.push({ url: res })
          })
          this.form.image_url = 1
        }
      } else {
        this.form['image_list'] = []
      }
    },
    handleSubmit() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          const that = this
          const params = {
            name: this.form.name,
            product_category_id: this.form.product_category_id.toString(),
            min_money: this.form.min_money.toString(),
            max_money: this.form.max_money.toString(),
            image_list: this.fileList.map((res) => {
              return res.url
            }),
            order: this.form.order.toString(),
            created_at: this.form.created_at,
            add_money_range: this.form.add_money_range,
            auction_session_id: this.form.auction_session_id,
            security_deposit: this.form.security_deposit,
            price: this.form.price
          }
          if (this.form._params && this.form._params.length > 0) {
            const array = []
            this.form._params.forEach((res) => {
              array.push({
                [res.model]: res.value
              })
            })
            params['params'] = array
          }
          // 上拍审核-待审核-审核通过传参status=2audit_status=1
          params['status'] = '2'
          params['audit_status'] = '1'
          this.$confirm('请确认是否同意上拍?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.listLoading = true
              putExhibition(this.form.id, params)
                .then(() => {
                  that.getList()
                  that.$notify({
                    title: '提示',
                    message: '操作成功',
                    type: 'success',
                    duration: 2000
                  })
                  that.dialogVisible = false
                  that.getList()
                })
                .catch(() => {
                  this.listLoading = false
                })
            })
            .catch(() => {})
        } else {
          this.$message.warning('还有必填项未填写')
        }
      })
    },
    // 拒绝
    handleRefuse(id) {
      const that = this
      this.$prompt('', '拒绝', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputPlaceholder: '请输入拒绝原因',
        inputErrorMessage: '拒绝原因不能为空',
        inputType: 'textarea',
        closeOnPressEscape: false,
        closeOnClickModal: false,
        closeOnHashChange: false,
        callback() {},
        beforeClose(action, instance, done) {
          if (action === 'confirm') {
            if (instance.confirmButtonLoading) {
              return false
            }
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '操作中...'
            putExhibition(id, {
              reject_remark: instance.inputValue,
              audit_status: '0'
            })
              .then(() => {
                that.getList()
                that.$notify({
                  title: '提示',
                  message: '操作成功',
                  type: 'success',
                  duration: 2000
                })
                done()
              })
              .finally(() => {
                instance.confirmButtonLoading = false
                instance.confirmButtonText = '确定'
              })
          } else {
            if (!instance.confirmButtonLoading) {
              done()
            } else {
              that.$message.warning('操作中，禁止关闭')
            }
          }
        }
      })
    },
    dialogClosed() {
      this.form = {}
      this.$refs['postForm'].resetFields()
    },
    getClassifyData() {
      getClassify().then((res) => {
        this.classifyOptions = res.data
      })
    },
    getFieldData() {
      getField({
        per_page: 100
      }).then((res) => {
        this.fieldOptions = res.data.data
      })
    },
    getList() {
      this.listLoading = true
      getExhibition(this.listQuery)
        .then((response) => {
          const { data, total } = response.data
          this.list = data
          this.total = total
        })
        .finally(() => {
          this.listLoading = false
        })
    }
  }
}
</script>

<style>
.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}

.hide .el-upload--picture-card {
  display: none;
}

.el-upload-list__item {
  transition: none !important;
}
</style>
